package com.meihuayishu.backend.service.impl;

import com.meihuayishu.backend.ai.AiService;
import com.meihuayishu.backend.algorithm.PersonalizedCalculator;
import com.meihuayishu.backend.algorithm.CommonCalculator;
import com.meihuayishu.backend.algorithm.WuxingAnalyzer;
import com.meihuayishu.backend.dto.DivinationResult;
import com.meihuayishu.backend.dto.DivinationResultV2;
import com.meihuayishu.backend.dto.TextDivinationRequest;
import com.meihuayishu.backend.entity.Hexagram;
import com.meihuayishu.backend.entity.User;
import com.meihuayishu.backend.entity.YaoCi;
import com.meihuayishu.backend.repository.UserRepository;
import com.meihuayishu.backend.service.CacheService;
import com.meihuayishu.backend.service.DivinationService;
import com.meihuayishu.backend.service.HexagramService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import jakarta.persistence.EntityNotFoundException;

import java.util.*;

/**
 * 增强版占卜服务实现
 * 支持个性化时间起卦和反馈闭环
 */
@Service
@Primary
@RequiredArgsConstructor
@Slf4j
public class DivinationServiceImpl implements DivinationService {
    
    private final AiService aiService;
    private final HexagramService hexagramService;
    private final CacheService cacheService;
    private final UserRepository userRepository;
    private final PersonalizedCalculator personalizedMeihuaCalculator;
    
    @Override
    public DivinationResult performTimeDivination(Long timestamp) {
        try {
            // 生成缓存键
            String cacheKey = "divination:time:" + timestamp;
            
            // 尝试从缓存获取结果
            DivinationResult cachedResult = cacheService.getDivinationResult(cacheKey);
            if (cachedResult != null) {
                log.debug("从缓存获取时间起卦结果，timestamp: {}", timestamp);
                return cachedResult;
            }
            
            // 使用梅花易数算法计算卦象
            CommonCalculator.MeihuaResult meihuaResult = CommonCalculator.calculateByTimestamp(timestamp);
            
            // 分析五行关系
            WuxingAnalyzer.WuxingRelationResult wuxingRelation = WuxingAnalyzer.analyzeGuaRelation(meihuaResult);
            
            // 生成六爻卦象
            DivinationContext context = generateHexagramFromMeihuaResult(meihuaResult);
            
            // 获取卦象信息
            Hexagram originalHexagram = hexagramService.getHexagramBySymbol(context.getOriginalSymbol()).orElse(null);
            Hexagram changedHexagram = hexagramService.getHexagramBySymbol(context.getChangedSymbol()).orElse(null);
            
            // 获取爻辞
            List<String> yaoCiList = getYaoCi(originalHexagram, context.getChangingLines());
            
            // 获取卦象直解
            String directInterpretation = getDirectInterpretation(originalHexagram, changedHexagram, context.getChangingLines());
            
            // 获取AI解读和行动建议
            String aiInterpretation = aiService.interpretDivination(
                originalHexagram != null ? originalHexagram.getName() : "未知卦",
                changedHexagram != null ? changedHexagram.getName() : "未知卦",
                null
            );
            
            List<String> suggestions = aiService.generateActionSuggestions(
                originalHexagram != null ? originalHexagram.getName() : "未知卦",
                changedHexagram != null ? changedHexagram.getName() : "未知卦",
                null
            );
            
            // 构建结果对象
            DivinationResult result = new DivinationResult();
            result.setOriginal(context.getOriginalHexagram());
            result.setChanged(context.getChangedHexagram());
            result.setChangingLines(context.getChangingLines());
            result.setOriginalName(originalHexagram != null ? originalHexagram.getName() : "未知卦");
            result.setChangedName(changedHexagram != null ? changedHexagram.getName() : "未知卦");
            
            // 设置新增的梅花易数相关信息
            result.setBodyGua(meihuaResult.getGuaBody());
            result.setUseGua(meihuaResult.getGuaUse());
            result.setHuGuaUp(meihuaResult.getGuaHuUp());
            result.setHuGuaDown(meihuaResult.getGuaHuDown());
            result.setFiveElementRelation(formatWuxingRelation(wuxingRelation));
            
            result.setYaoCi(yaoCiList);
            result.setDirectInterpretation(directInterpretation);
            result.setAiInterpretation(aiInterpretation);
            result.setSuggestions(suggestions);
            
            // 缓存结果，有效期30分钟
            cacheService.cacheDivinationResult(cacheKey, result, 1800);
            
            return result;
        } catch (Exception e) {
            log.error("时间起卦失败", e);
            return createErrorResult("时间起卦失败: " + e.getMessage());
        }
    }
    
    @Override
    public DivinationResult performPersonalizedTimeDivination(Long timestamp, Long userId, String question) {
        return performPersonalizedTimeDivination(timestamp, userId, question, null, null, null, true, true, null);
    }
    
    /**
     * 执行增强版个性化时间起卦
     * @param timestamp 时间戳
     * @param userId 用户ID
     * @param question 问题
     * @param temporaryCity 临时指定城市（可选）
     * @param temporaryMood 临时指定心情（可选）
     * @param temporaryQuestion 临时指定问题（可选）
     * @param useRealSolarTime 是否使用真太阳时（可选）
     * @param applyFeedback 是否应用历史反馈调整（可选）
     * @param priorityFactor 优先因素（可选）
     * @return 占卜结果
     */
    public DivinationResult performPersonalizedTimeDivination(
            Long timestamp, 
            Long userId, 
            String question,
            String temporaryCity,
            String temporaryMood,
            String temporaryQuestion,
            Boolean useRealSolarTime,
            Boolean applyFeedback,
            Integer priorityFactor) {
        try {
            // 获取用户信息
            User user = userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
            
            // 应用临时覆盖信息
            User tempUser = new User();
            tempUser.setId(user.getId());
            tempUser.setUsername(user.getUsername());
            tempUser.setPassword(user.getPassword());
            tempUser.setBirthDate(user.getBirthDate());
            tempUser.setBirthLocation(user.getBirthLocation());
            tempUser.setCurrentCity(temporaryCity != null ? temporaryCity : user.getCurrentCity());
            tempUser.setGender(user.getGender());
            tempUser.setMoodStatus(temporaryMood != null ? temporaryMood : user.getMoodStatus());
            
            // 使用临时问题（如果有）
            String effectiveQuestion = temporaryQuestion != null ? temporaryQuestion : question;
            
            // 生成缓存键（包含用户ID和临时参数确保个性化）
            String cacheKey = "divination:personalized:" + timestamp + ":" + userId + ":" 
                + (temporaryCity != null ? temporaryCity : "") + ":" 
                + (temporaryMood != null ? temporaryMood : "") + ":" 
                + (useRealSolarTime != null ? useRealSolarTime : true) + ":" 
                + (applyFeedback != null ? applyFeedback : true);
            
            // 尝试从缓存获取结果
            DivinationResult cachedResult = cacheService.getDivinationResult(cacheKey);
            if (cachedResult != null) {
                log.debug("从缓存获取个性化时间起卦结果，timestamp: {}, userId: {}", timestamp, userId);
                return cachedResult;
            }
            
            // 使用增强版个性化梅花易数算法计算卦象
            CommonCalculator.MeihuaResult meihuaResult;
            
            // 根据优先因素调整计算逻辑
            if (priorityFactor != null) {
                log.debug("使用优先因素 {} 进行个性化计算", priorityFactor);
                // 这里可以根据priorityFactor调整计算逻辑
                // 1:城市, 2:心情, 3:生辰
                meihuaResult = personalizedMeihuaCalculator.calculatePersonalized(timestamp, tempUser, priorityFactor);
            } else {
                meihuaResult = personalizedMeihuaCalculator.calculatePersonalized(timestamp, tempUser);
            }
            
            // 是否应用真太阳时修正
            if (useRealSolarTime != null && !useRealSolarTime) {
                log.debug("跳过真太阳时修正");
                // 如果不使用真太阳时，可以在这里进行额外处理
            }
            
            // 是否应用历史反馈调整
            if (applyFeedback != null && !applyFeedback) {
                log.debug("跳过历史反馈调整");
                // 如果不应用历史反馈，可以在这里进行额外处理
            }
            
            // 分析五行关系
            WuxingAnalyzer.WuxingRelationResult wuxingRelation = WuxingAnalyzer.analyzeGuaRelation(meihuaResult);
            
            // 生成六爻卦象
            DivinationContext context = generateHexagramFromMeihuaResult(meihuaResult);
            
            // 获取卦象信息
            Hexagram originalHexagram = hexagramService.getHexagramBySymbol(context.getOriginalSymbol()).orElse(null);
            Hexagram changedHexagram = hexagramService.getHexagramBySymbol(context.getChangedSymbol()).orElse(null);
            
            // 获取爻辞
            List<String> yaoCiList = getYaoCi(originalHexagram, context.getChangingLines());
            
            // 获取卦象直解
            String directInterpretation = getDirectInterpretation(originalHexagram, changedHexagram, context.getChangingLines());
            
            // 构建个性化AI解读提示词
            String personalizedPrompt = buildPersonalizedPrompt(user, originalHexagram, changedHexagram, question);
            
            // 获取个性化AI解读和行动建议
            String aiInterpretation = aiService.interpretDivination(
                originalHexagram != null ? originalHexagram.getName() : "未知卦",
                changedHexagram != null ? changedHexagram.getName() : "未知卦",
                personalizedPrompt
            );
            
            List<String> suggestions = aiService.generateActionSuggestions(
                originalHexagram != null ? originalHexagram.getName() : "未知卦",
                changedHexagram != null ? changedHexagram.getName() : "未知卦",
                personalizedPrompt
            );
            
            // 构建结果对象
            DivinationResult result = new DivinationResult();
            result.setOriginal(context.getOriginalHexagram());
            result.setChanged(context.getChangedHexagram());
            result.setChangingLines(context.getChangingLines());
            result.setOriginalName(originalHexagram != null ? originalHexagram.getName() : "未知卦");
            result.setChangedName(changedHexagram != null ? changedHexagram.getName() : "未知卦");
            
            // 设置新增的梅花易数相关信息
            result.setBodyGua(meihuaResult.getGuaBody());
            result.setUseGua(meihuaResult.getGuaUse());
            result.setHuGuaUp(meihuaResult.getGuaHuUp());
            result.setHuGuaDown(meihuaResult.getGuaHuDown());
            result.setFiveElementRelation(formatWuxingRelation(wuxingRelation));
            
            result.setYaoCi(yaoCiList);
            result.setDirectInterpretation(directInterpretation);
            result.setAiInterpretation(aiInterpretation);
            result.setSuggestions(suggestions);
            result.setPersonalized(true); // 标记为个性化结果
            
            // 缓存结果，有效期30分钟
            cacheService.cacheDivinationResult(cacheKey, result, 1800);
            
            return result;
        } catch (Exception e) {
            log.error("个性化时间起卦失败", e);
            return createErrorResult("个性化时间起卦失败: " + e.getMessage());
        }
    }
    
    @Override
    public DivinationResult performNumberDivination(Integer number1, Integer number2) {
        try {
            // 生成缓存键
            String cacheKey = "divination:number:" + number1 + ":" + number2;
            
            // 尝试从缓存获取结果
            DivinationResult cachedResult = cacheService.getDivinationResult(cacheKey);
            if (cachedResult != null) {
                log.debug("从缓存获取数字起卦结果，number1: {}, number2: {}", number1, number2);
                return cachedResult;
            }
            
            // 使用梅花易数算法计算卦象
            CommonCalculator.MeihuaResult meihuaResult = CommonCalculator.calculateByNumbers(
                number1 != null ? number1 : 0,
                number2 != null ? number2 : 0
            );
            
            // 分析五行关系
            WuxingAnalyzer.WuxingRelationResult wuxingRelation = WuxingAnalyzer.analyzeGuaRelation(meihuaResult);
            
            // 生成六爻卦象
            DivinationContext context = generateHexagramFromMeihuaResult(meihuaResult);
            
            // 获取卦象信息
            Hexagram originalHexagram = hexagramService.getHexagramBySymbol(context.getOriginalSymbol()).orElse(null);
            Hexagram changedHexagram = hexagramService.getHexagramBySymbol(context.getChangedSymbol()).orElse(null);
            
            // 获取爻辞
            List<String> yaoCiList = getYaoCi(originalHexagram, context.getChangingLines());
            
            // 获取卦象直解
            String directInterpretation = getDirectInterpretation(originalHexagram, changedHexagram, context.getChangingLines());
            
            // 获取AI解读和行动建议
            String aiInterpretation = aiService.interpretDivination(
                originalHexagram != null ? originalHexagram.getName() : "未知卦",
                changedHexagram != null ? changedHexagram.getName() : "未知卦",
                null
            );
            
            List<String> suggestions = aiService.generateActionSuggestions(
                originalHexagram != null ? originalHexagram.getName() : "未知卦",
                changedHexagram != null ? changedHexagram.getName() : "未知卦",
                null
            );
            
            // 构建结果对象
            DivinationResult result = new DivinationResult();
            result.setOriginal(context.getOriginalHexagram());
            result.setChanged(context.getChangedHexagram());
            result.setChangingLines(context.getChangingLines());
            result.setOriginalName(originalHexagram != null ? originalHexagram.getName() : "未知卦");
            result.setChangedName(changedHexagram != null ? changedHexagram.getName() : "未知卦");
            
            // 设置新增的梅花易数相关信息
            result.setBodyGua(meihuaResult.getGuaBody());
            result.setUseGua(meihuaResult.getGuaUse());
            result.setHuGuaUp(meihuaResult.getGuaHuUp());
            result.setHuGuaDown(meihuaResult.getGuaHuDown());
            result.setFiveElementRelation(formatWuxingRelation(wuxingRelation));
            
            result.setYaoCi(yaoCiList);
            result.setDirectInterpretation(directInterpretation);
            result.setAiInterpretation(aiInterpretation);
            result.setSuggestions(suggestions);
            
            // 缓存结果，有效期30分钟
            cacheService.cacheDivinationResult(cacheKey, result, 1800);
            
            return result;
        } catch (Exception e) {
            log.error("数字起卦失败", e);
            return createErrorResult("数字起卦失败: " + e.getMessage());
        }
    }
    
    @Override
    public String interpretDivination(String originalName, String changedName, String question) {
        return aiService.interpretDivination(originalName, changedName, question);
    }
    
    @Override
    public String interpretDivination(String originalName, String changedName, String question, String aiProvider) {
        return aiService.interpretDivination(originalName, changedName, question, aiProvider);
    }
    
    @Override
    public DivinationResultV2 performImageDivination(String question, org.springframework.web.multipart.MultipartFile image, String algorithm, Boolean extractFeatures) {
        try {
            log.info("开始图片起卦，问题: {}, 算法: {}", question, algorithm);
            
            // 根据图片生成哈希值
            int imageHash = generateImageHash(image, algorithm);
            
            // 使用哈希值作为数字起卦的输入
            int number1 = imageHash % 999 + 1;
            int number2 = (imageHash / 1000) % 999 + 1;
            
            DivinationResult oldResult = performNumberDivination(number1, number2);
            
            // 转换为 V2 格式
            return convertToV2Format(oldResult, "IMAGE", question, System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("图片起卦失败", e);
            throw new RuntimeException("图片起卦失败: " + e.getMessage());
        }
    }
    
    @Override
    public DivinationResultV2 performTextDivination(TextDivinationRequest request) {
        try {
            log.info("开始文本起卦，问题: {}, 类型: {}", request.getQuestion(), request.getSourceType());
            
            // 根据文本内容生成哈希值
            int textHash = generateTextHash(request.getInputText(), request.getAlgorithm());
            
            // 使用哈希值作为数字起卦的输入
            int number1 = textHash % 999 + 1;
            int number2 = (textHash / 1000) % 999 + 1;
            
            DivinationResult oldResult = performNumberDivination(number1, number2);
            
            // 转换为 V2 格式
            return convertToV2Format(oldResult, "TEXT", request.getQuestion(), System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("文本起卦失败", e);
            throw new RuntimeException("文本起卦失败: " + e.getMessage());
        }
    }
    
    /**
     * 构建个性化AI解读提示词
     * @param user 用户信息
     * @param originalHexagram 本卦
     * @param changedHexagram 变卦
     * @param question 问题
     * @return 个性化提示词
     */
    private String buildPersonalizedPrompt(User user, Hexagram originalHexagram, Hexagram changedHexagram, String question) {
        StringBuilder prompt = new StringBuilder();
        
        // 添加用户基本信息
        prompt.append("用户为");
        prompt.append(user.getGender() != null ? user.getGender() : "未知性别");
        
        // 添加用户当前城市和五行属性
        if (user.getCurrentCity() != null) {
            prompt.append("，现居").append(user.getCurrentCity());
            // 这里应该从CityElementData获取五行属性，简化处理
            String element = "土"; // 默认值
            prompt.append("（五行属").append(element).append("）");
        }
        
        // 添加用户心情
        if (user.getMoodStatus() != null) {
            prompt.append("，当前心情为").append(user.getMoodStatus());
        }
        
        // 添加卦象信息
        prompt.append("。\n请结合");
        prompt.append(originalHexagram != null ? originalHexagram.getName() : "未知卦");
        prompt.append("卦象");
        
        // 添加问题（如果有）
        if (question != null && !question.isEmpty()) {
            prompt.append("，针对问题「").append(question).append("」");
        }
        
        // 添加解读要求
        prompt.append("，用现代语言解读其运势，避免迷信表述。");
        
        return prompt.toString();
    }
    
    /**
     * 根据梅花易数结果生成六爻卦象
     * @param meihuaResult 梅花易数结果
     * @return 卦象上下文
     */
    private DivinationContext generateHexagramFromMeihuaResult(CommonCalculator.MeihuaResult meihuaResult) {
        // 八卦对应的二进制表示（从下往上，0表示阴爻，1表示阳爻）
        Map<String, String> guaToBinary = createGuaToBinaryMap();
        
        // 获取上下卦的三爻
        String upperSymbol = guaToBinary.get(meihuaResult.getGuaUp());
        String lowerSymbol = guaToBinary.get(meihuaResult.getGuaDown());
        
        // 组合成六爻卦象
        String originalSymbol = lowerSymbol + upperSymbol;
        
        // 计算变卦
        String changedSymbol = calculateChangedHexagram(originalSymbol, meihuaResult.getChangeYao());
        
        // 转换为整数数组
        List<Integer> originalHexagram = symbolToHexagram(originalSymbol);
        List<Integer> changedHexagram = symbolToHexagram(changedSymbol);
        List<Integer> changingLines = Arrays.asList(meihuaResult.getChangeYao());
        
        return new DivinationContext(
            originalHexagram,
            changedHexagram,
            changingLines,
            originalSymbol,
            changedSymbol
        );
    }
    
    /**
     * 计算变卦
     * @param originalSymbol 原卦符号
     * @param changingLine 动爻位置
     * @return 变卦符号
     */
    private String calculateChangedHexagram(String originalSymbol, int changingLine) {
        StringBuilder changedSymbol = new StringBuilder(originalSymbol);
        // 动爻位置从1开始计数，字符串索引从0开始
        int index = changingLine - 1;
        if (index >= 0 && index < originalSymbol.length()) {
            char currentYao = originalSymbol.charAt(index);
            // 变爻：阳爻变阴爻，阴爻变阳爻
            char changedYao = (currentYao == '1') ? '0' : '1';
            changedSymbol.setCharAt(index, changedYao);
        }
        return changedSymbol.toString();
    }
    
    /**
     * 创建八卦到二进制的映射表
     * @return 八卦到二进制的映射表
     */
    private Map<String, String> createGuaToBinaryMap() {
        Map<String, String> map = new HashMap<>();
        map.put("乾", "111");
        map.put("坤", "000");
        map.put("震", "100");
        map.put("巽", "010");
        map.put("坎", "001");
        map.put("离", "110");
        map.put("艮", "101");
        map.put("兑", "011");
        return map;
    }
    
    /**
     * 将卦象符号转换为整数列表
     * @param symbol 卦象符号
     * @return 整数列表
     */
    private List<Integer> symbolToHexagram(String symbol) {
        List<Integer> hexagram = new ArrayList<>();
        for (char c : symbol.toCharArray()) {
            hexagram.add(Character.getNumericValue(c));
        }
        return hexagram;
    }
    
    /**
     * 获取爻辞
     * @param hexagram 卦象
     * @param changingLines 变爻位置
     * @return 爻辞列表
     */
    private List<String> getYaoCi(Hexagram hexagram, List<Integer> changingLines) {
        List<String> yaoCiList = new ArrayList<>();
        if (hexagram != null && changingLines != null && !changingLines.isEmpty()) {
            for (Integer line : changingLines) {
                YaoCi yaoCi = hexagramService.getYaoCiByHexagramIdAndPosition(hexagram.getId(), line);
                if (yaoCi != null) {
                    yaoCiList.add(yaoCi.getYaoCiText());
                } else {
                    yaoCiList.add("第" + line + "爻：爻辞内容示例");
                }
            }
        }
        return yaoCiList;
    }
    
    /**
     * 获取卦象直解
     * @param originalHexagram 本卦
     * @param changedHexagram 变卦
     * @param changingLines 变爻位置
     * @return 卦象直解
     */
    private String getDirectInterpretation(Hexagram originalHexagram, Hexagram changedHexagram, List<Integer> changingLines) {
        StringBuilder interpretation = new StringBuilder();
        
        // 添加卦象名称
        interpretation.append("《")
            .append(originalHexagram != null ? originalHexagram.getName() : "未知卦")
            .append("》之《")
            .append(changedHexagram != null ? changedHexagram.getName() : "未知卦")
            .append("》");
        
        // 添加变爻信息
        if (changingLines != null && !changingLines.isEmpty()) {
            interpretation.append("，变爻在第").append(changingLines.get(0)).append("爻");
        }
        
        // 添加卦象的基本含义
        if (originalHexagram != null) {
            interpretation.append("\n\n本卦《").append(originalHexagram.getName()).append("》：")
                .append(originalHexagram.getDescription() != null ? originalHexagram.getDescription() : "卦象描述");
        }
        
        if (changedHexagram != null && !changedHexagram.getName().equals(originalHexagram != null ? originalHexagram.getName() : "")) {
            interpretation.append("\n\n变卦《").append(changedHexagram.getName()).append("》：")
                .append(changedHexagram.getDescription() != null ? changedHexagram.getDescription() : "卦象描述");
        }
        
        // 添加卦辞
        if (originalHexagram != null && originalHexagram.getHexagramMeaning() != null) {
            interpretation.append("\n\n卦辞：").append(originalHexagram.getHexagramMeaning());
        }
        
        // 添加变爻的爻辞
        if (changingLines != null && !changingLines.isEmpty() && originalHexagram != null) {
            for (Integer line : changingLines) {
                YaoCi yaoCi = hexagramService.getYaoCiByHexagramIdAndPosition(originalHexagram.getId(), line);
                if (yaoCi != null) {
                    interpretation.append("\n\n第").append(line).append("爻：").append(yaoCi.getYaoCiText());
                }
            }
        }
        
        return interpretation.toString();
    }
    
    /**
     * 格式化五行关系分析结果
     * @param wuxingRelation 五行关系分析结果
     * @return 格式化的五行关系描述
     */
    private String formatWuxingRelation(WuxingAnalyzer.WuxingRelationResult wuxingRelation) {
        StringBuilder relation = new StringBuilder();
        relation.append("五行关系分析：\n");
        relation.append("主卦关系：").append(wuxingRelation.getMainRelation()).append("\n");
        relation.append("体用关系：").append(wuxingRelation.getBodyUseRelation()).append("\n");
        relation.append("互卦关系：").append(wuxingRelation.getHuRelation()).append("\n");
        relation.append("变卦关系：").append(wuxingRelation.getChangeRelation());
        return relation.toString();
    }
    
    /**
     * 创建错误结果
     * @param message 错误消息
     * @return 错误结果
     */
    private DivinationResult createErrorResult(String message) {
        DivinationResult result = new DivinationResult();
        result.setOriginal(Arrays.asList(0, 0, 0, 0, 0, 0));
        result.setChanged(Arrays.asList(0, 0, 0, 0, 0, 0));
        result.setChangingLines(Arrays.asList());
        result.setOriginalName("错误卦");
        result.setChangedName("错误卦");
        result.setYaoCi(Arrays.asList());
        result.setDirectInterpretation(message);
        result.setAiInterpretation(message);
        result.setSuggestions(Arrays.asList("请稍后重试"));
        return result;
    }
    
    /**
     * 卦象上下文类
     */
    private static class DivinationContext {
        private final List<Integer> originalHexagram;
        private final List<Integer> changedHexagram;
        private final List<Integer> changingLines;
        private final String originalSymbol;
        private final String changedSymbol;
        
        public DivinationContext(List<Integer> originalHexagram, List<Integer> changedHexagram,
                               List<Integer> changingLines, String originalSymbol, String changedSymbol) {
            this.originalHexagram = originalHexagram;
            this.changedHexagram = changedHexagram;
            this.changingLines = changingLines;
            this.originalSymbol = originalSymbol;
            this.changedSymbol = changedSymbol;
        }
        
        public List<Integer> getOriginalHexagram() { return originalHexagram; }
        public List<Integer> getChangedHexagram() { return changedHexagram; }
        public List<Integer> getChangingLines() { return changingLines; }
        public String getOriginalSymbol() { return originalSymbol; }
        public String getChangedSymbol() { return changedSymbol; }
    }
    
    /**
     * 生成图片哈希值
     * @param image 图片文件
     * @param algorithm 算法类型
     * @return 哈希值
     */
    private int generateImageHash(org.springframework.web.multipart.MultipartFile image, String algorithm) {
        try {
            byte[] imageBytes = image.getBytes();
            int hash = 0;
            
            switch (algorithm) {
                case "COLOR_HASH":
                    // 基于颜色的简单哈希算法
                    for (byte b : imageBytes) {
                        hash = hash * 31 + (b & 0xFF);
                    }
                    break;
                case "EDGE_DETECTION":
                    // 基于边缘检测的哈希算法（简化版）
                    hash = image.getOriginalFilename().hashCode() + (int)image.getSize();
                    break;
                case "PIXEL_ANALYSIS":
                default:
                    // 默认像素分析算法
                    hash = java.util.Arrays.hashCode(imageBytes);
                    break;
            }
            
            return Math.abs(hash);
        } catch (Exception e) {
            log.error("生成图片哈希失败", e);
            return image.getOriginalFilename().hashCode();
        }
    }
    
    /**
     * 生成文本哈希值
     * @param text 输入文本
     * @param algorithm 算法类型
     * @return 哈希值
     */
    private int generateTextHash(String text, String algorithm) {
        try {
            switch (algorithm) {
                case "WORD_COUNT":
                    // 基于词汇统计的哈希
                    return text.length() * text.replace(" ", "").length();
                case "SEMANTIC":
                    // 语义分析哈希（简化版）
                    int semanticHash = 0;
                    for (char c : text.toCharArray()) {
                        semanticHash += c * (c % 7 + 1);
                    }
                    return Math.abs(semanticHash);
                case "TEXT_HASH":
                default:
                    // 默认文本哈希
                    return Math.abs(text.hashCode());
            }
        } catch (Exception e) {
            log.error("生成文本哈希失败", e);
            return Math.abs(text.hashCode());
        }
    }
    
    /**
     * 将旧的DivinationResult转换为新的DivinationResultV2格式
     * @param oldResult 旧格式结果
     * @param divinationType 占卜类型
     * @param question 问题
     * @param timestamp 时间戳
     * @return V2格式结果
     */
    private com.meihuayishu.backend.dto.DivinationResultV2 convertToV2Format(DivinationResult oldResult, String divinationType, String question, Long timestamp) {
        // 构建三元组信息
        com.meihuayishu.backend.dto.DivinationResultV2.TrigramInfo upperTrigram = com.meihuayishu.backend.dto.DivinationResultV2.TrigramInfo.builder()
                .name(extractTrigramName(oldResult.getOriginalName(), true))
                .symbol(getTrigramSymbol(extractTrigramName(oldResult.getOriginalName(), true)))
                .element(getTrigramElement(extractTrigramName(oldResult.getOriginalName(), true)))
                .build();
                
        com.meihuayishu.backend.dto.DivinationResultV2.TrigramInfo lowerTrigram = com.meihuayishu.backend.dto.DivinationResultV2.TrigramInfo.builder()
                .name(extractTrigramName(oldResult.getOriginalName(), false))
                .symbol(getTrigramSymbol(extractTrigramName(oldResult.getOriginalName(), false)))
                .element(getTrigramElement(extractTrigramName(oldResult.getOriginalName(), false)))
                .build();
        
        // 构建卦象信息
        com.meihuayishu.backend.dto.DivinationResultV2.HexagramInfo hexagram = com.meihuayishu.backend.dto.DivinationResultV2.HexagramInfo.builder()
                .name(oldResult.getOriginalName())
                .code(convertNameToCode(oldResult.getOriginalName()))
                .upperTrigram(upperTrigram)
                .lowerTrigram(lowerTrigram)
                .hexagramText(oldResult.getDirectInterpretation())
                .elementRelation(oldResult.getFiveElementRelation())
                .build();
        
        // 构建计算信息
        com.meihuayishu.backend.dto.DivinationResultV2.CalculationInfo calculation = com.meihuayishu.backend.dto.DivinationResultV2.CalculationInfo.builder()
                .formula("梅花易数算法")
                .build();
        
        if (timestamp != null) {
            java.time.LocalDateTime dateTime = java.time.LocalDateTime.ofInstant(
                java.time.Instant.ofEpochMilli(timestamp), java.time.ZoneId.systemDefault());
            calculation.setYear(dateTime.getYear());
            calculation.setMonth(dateTime.getMonthValue());
            calculation.setDay(dateTime.getDayOfMonth());
            calculation.setHour(dateTime.getHour());
            calculation.setMinute(dateTime.getMinute());
        }
        
        return com.meihuayishu.backend.dto.DivinationResultV2.builder()
                .divinationId("div_" + System.currentTimeMillis())
                .question(question)
                .divinationType(divinationType)
                .divinationTime(java.time.LocalDateTime.now())
                .algorithm("TRADITIONAL")
                .hexagram(hexagram)
                .calculation(calculation)
                .build();
    }
    
    /**
     * 从卦名中提取三元组名称
     * @param hexagramName 卦象名称
     * @param isUpper 是否为上卦
     * @return 三元组名称
     */
    private String extractTrigramName(String hexagramName, boolean isUpper) {
        if (hexagramName == null || hexagramName.length() < 2) {
            return "乾";
        }
        
        // 简化的三元组提取逻辑
        if (isUpper) {
            return hexagramName.substring(0, 1);
        } else {
            return hexagramName.substring(1, 2);
        }
    }
    
    /**
     * 获取三元组符号
     * @param trigramName 三元组名称
     * @return 符号
     */
    private String getTrigramSymbol(String trigramName) {
        return switch (trigramName) {
            case "乾" -> "☰";
            case "坤" -> "☷";
            case "离" -> "☲";
            case "震" -> "☳";
            case "巽" -> "☴";
            case "坎" -> "☵";
            case "艮" -> "☶";
            case "兑" -> "☱";
            default -> "☰";
        };
    }
    
    /**
     * 获取三元组对应的五行
     * @param trigramName 三元组名称
     * @return 五行
     */
    private String getTrigramElement(String trigramName) {
        return switch (trigramName) {
            case "乾" -> "金";
            case "坤" -> "土";
            case "离" -> "火";
            case "震" -> "木";
            case "巽" -> "木";
            case "坎" -> "水";
            case "艮" -> "土";
            case "兑" -> "金";
            default -> "土";
        };
    }
    
    /**
     * 将卦名转换为编码
     * @param hexagramName 卦象名称
     * @return 编码
     */
    private String convertNameToCode(String hexagramName) {
        if (hexagramName == null) {
            return "UNKNOWN";
        }
        return hexagramName.replace("为", "_WEI_")
                .replace("天", "TIAN")
                .replace("地", "DI")
                .replace("水", "SHUI")
                .replace("火", "HUO")
                .replace("山", "SHAN")
                .replace("泽", "ZE")
                .replace("风", "FENG")
                .replace("雷", "LEI")
                .toUpperCase();
    }
}